//
//  SLRoutePush.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/2/23.
//

#import "SLRoutePush.h"
#import <YYKit.h>
#import "SLWebViewController.h"
#import "CustomTabBarController.h"
#import "OriginData.h"
#import "CYLTabBarControllerConfig.h"
#import "BasicTabBarController.h"

#import "Home1ViewController.h"
#import "Home2ViewController.h"
#import "SLOrderViewController.h"
#import "SLMineViewController.h"

@implementation SLRoutePush


+ (void)route:(NSString *)router parameter:(NSDictionary *)parameter {
    UIViewController *ctrl = UIApplication.sharedApplication.keyWindow.rootViewController;
    UIViewController *topViewController = ctrl;
    if ([ctrl isKindOfClass:UINavigationController.class]) {
        topViewController = ((UINavigationController *)ctrl).viewControllers.lastObject;
    } else if ([ctrl isKindOfClass:UITabBarController.class]) {
        UINavigationController *nav = ((UITabBarController *)ctrl).selectedViewController;
        topViewController = nav.viewControllers.lastObject;
    }
    
    if ([router hasPrefix:@"http://"] || [router hasPrefix:@"https://"]) {
        // H5网页
        SLWebViewController *web = [SLWebViewController new];
        // 拼接公参
        NSDictionary *dict = [RequestCommonParameter parameter];
        // 拼接参数到URL
        NSString *finalURL = [self appendParameters:dict toURL:router];
        
        // 加载URL
        [web loadURL:finalURL];
        [topViewController.navigationController pushViewController:web animated:YES];
    } else if ([router hasPrefix:@"sule://"]) {
        // 自定义的路由
        NSURL *url = [NSURL URLWithString:router];
        NSString *detail = [OriginData schemeOrigin:url.lastPathComponent];
        NSDictionary *dict = [self queryKeyValue:url];
        if ([detail isEqualToString:@"setting"]) {
            if (![topViewController isKindOfClass:NSClassFromString(@"SLSettingsViewController")]) {
                [self route:@"SLSettingsViewController" parameter:nil];
            }
        } else if ([detail isEqualToString:@"main"]) {
            [topViewController.navigationController popToRootViewControllerAnimated:YES];
            UITabBarController *tabbarCtrl = (UITabBarController *)UIApplication.sharedApplication.keyWindow.rootViewController;
            tabbarCtrl.selectedIndex = 0;
        } else if ([detail isEqualToString:@"login"]) {
            if (![topViewController isKindOfClass:NSClassFromString(@"SLLoginViewController")]) {
                [self route:@"SLLoginViewController" parameter:nil];
            }
        } else if ([detail isEqualToString:@"productDetail"]) {
            if (![topViewController isKindOfClass:NSClassFromString(@"SLCoreCertificationViewController")]) {
                [self route:@"SLCoreCertificationViewController" parameter:@{@"productId": dict[@"scenery"] ?: @""}];
            }
        }
    } else {
        UIViewController *ctrl = [NSClassFromString(router) new];
        ctrl.hidesBottomBarWhenPushed = YES;
        if ([parameter isKindOfClass:NSDictionary.class]) {
            for (NSString *key in parameter.allKeys) {
                [ctrl setValue:parameter[key] forKey:key];
            }
        }
        [topViewController.navigationController pushViewController:ctrl animated:YES];
    }
}

+ (NSString *)appendParameters:(NSDictionary *)parameters toURL:(NSString *)urlString {
    @try {
        // 1. 参数验证
        if (![urlString isKindOfClass:[NSString class]] || 
            urlString.length == 0 || 
            ![parameters isKindOfClass:[NSDictionary class]]) {
            return urlString;
        }
        
        // 2. 创建URL组件
        NSURLComponents *components = [[NSURLComponents alloc] initWithString:urlString];
        if (!components) return urlString;
        
        // 3. 获取现有参数
        NSMutableDictionary *existingParams = [NSMutableDictionary dictionary];
        for (NSURLQueryItem *item in components.queryItems) {
            if (item.name && item.value) {
                existingParams[item.name] = item.value;
            }
        }
        
        // 4. 合并新参数（可以在这里添加自定义的合并规则）
        NSMutableDictionary *mergedParams = [NSMutableDictionary dictionaryWithDictionary:existingParams];
        [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([key isKindOfClass:[NSString class]] && obj) {
                mergedParams[key] = [NSString stringWithFormat:@"%@", obj];
            }
        }];
        
        // 5. 创建新的查询参数
        NSMutableArray<NSURLQueryItem *> *queryItems = [NSMutableArray array];
        [mergedParams enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
            NSURLQueryItem *item = [[NSURLQueryItem alloc] initWithName:key value:obj];
            [queryItems addObject:item];
        }];
        
        // 6. 按键排序（可选，使URL更规范）
        [queryItems sortUsingComparator:^NSComparisonResult(NSURLQueryItem *item1, NSURLQueryItem *item2) {
            return [item1.name compare:item2.name];
        }];
        
        // 7. 设置新的查询参数
        components.queryItems = queryItems;
        
        // 8. 返回完整URL
        return components.URL.absoluteString ?: urlString;
    } @catch (NSException *exception) {
        NSLog(@"URL参数拼接异常: %@", exception);
        return urlString;
    }
}

+ (NSDictionary *)queryKeyValue:(NSURL *)url {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    // 使用 NSURLComponents 解析 URL
    NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
    // 获取查询参数
    NSArray<NSURLQueryItem *> *queryItems = components.queryItems;
    
    // 遍历查询参数
    for (NSURLQueryItem *item in queryItems) {
        if (item.name && item.value) {
            [dict setValue:item.value forKey:item.name];
        }
    }
    return dict;
}

+ (void)rootRoute:(NSString *)root {
    UIApplication.sharedApplication.keyWindow.rootViewController = [[UINavigationController alloc] initWithRootViewController:[NSClassFromString(root) new]];
}

+ (void)routeMain {
    [HomeRequestProvider requestNewHomeWithSuccess:^(NSDictionary * _Nonnull dict) {
        UIWindow *window = UIApplication.sharedApplication.keyWindow;
        NSString *peppers = [OriginData peppersOrigin:dict[@"breathe"][@"peppers"]];
        
        // 创建 UITabBarController
        BasicTabBarController *tabBarController = [[BasicTabBarController alloc] init];
        tabBarController.tabBar.translucent = NO;
        tabBarController.tabBar.backgroundColor = UIColorHex(#1B1B1B);
        tabBarController.isMustLocation = [dict[@"atom"] boolValue];
        // 设置 UITabBar 的背景颜色为不透明
        [[UITabBar appearance] setBarTintColor:UIColorHex(#1B1B1B)]; // 你可以将 [UIColor whiteColor] 替换为任何你想要的颜色
        // 设置 UITabBar 为不透明
        [[UITabBar appearance] setTranslucent:NO];
        
        
        // 创建第一个视图控制器
        Home1ViewController *home1Ctrl = [Home1ViewController new];
        UIImage *home_normal = [[UIImage imageNamed:@"tab_home_normal"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImage *home_select = [[UIImage imageNamed:@"tab_home_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UITabBarItem *homeItem = [[UITabBarItem alloc] initWithTitle:nil image:home_normal selectedImage:home_select];
        homeItem.imageInsets = UIEdgeInsetsMake(11, 0, -11, 0);
        home1Ctrl.tabBarItem = homeItem;
        
        Home2ViewController *home2Ctrl = [Home2ViewController new];
        home2Ctrl.tabBarItem = homeItem;
        
        // 赋值
        home1Ctrl.homeModel = dict;
        home2Ctrl.homeModel = dict;
        
        // 创建第二个视图控制器
        SLOrderViewController *orderCtrl = [SLOrderViewController new];
        UIImage *order_normal = [[UIImage imageNamed:@"tab_order_normal"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImage *order_select = [[UIImage imageNamed:@"tab_order_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UITabBarItem *orderItem = [[UITabBarItem alloc] initWithTitle:nil image:order_normal selectedImage:order_select];
        orderItem.imageInsets = UIEdgeInsetsMake(11, 0, -11, 0);
        orderCtrl.tabBarItem = orderItem;
        
        // 创建第三个视图控制器
        SLMineViewController *mineCtrl = [SLMineViewController new];
        UIImage *mine_normal = [[UIImage imageNamed:@"tab_mine_normal"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImage *mine_select = [[UIImage imageNamed:@"tab_mine_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UITabBarItem *mineItem = [[UITabBarItem alloc] initWithTitle:nil image:mine_normal selectedImage:mine_select];
        mineItem.imageInsets = UIEdgeInsetsMake(11, 0, -11, 0);
        mineCtrl.tabBarItem = mineItem;
        
        if ([peppers isEqualToString:@"LARGE_CARD"]) {
            // 将视图控制器添加到 UITabBarController
            tabBarController.viewControllers = @[
                [[BasicNavigationController alloc] initWithRootViewController:home1Ctrl],
                [[BasicNavigationController alloc] initWithRootViewController:orderCtrl],
                [[BasicNavigationController alloc] initWithRootViewController:mineCtrl],
            ];
        } else {
            // 将视图控制器添加到 UITabBarController
            tabBarController.viewControllers = @[
                [[BasicNavigationController alloc] initWithRootViewController:home2Ctrl],
                [[BasicNavigationController alloc] initWithRootViewController:orderCtrl],
                [[BasicNavigationController alloc] initWithRootViewController:mineCtrl],
            ];
        }
        
        window.rootViewController = tabBarController;
    } failure:^(YTKRequest * _Nonnull request) {
    }];
}

/// 退到首页
+ (void)routeHomeController {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    UITabBarController *tabBarController = (UITabBarController *)window.rootViewController;
    UIViewController *topViewController = nil;
    if ([tabBarController isKindOfClass:UINavigationController.class]) {
        topViewController = ((UINavigationController *)tabBarController).viewControllers.lastObject;
    } else if ([tabBarController isKindOfClass:UITabBarController.class]) {
        UINavigationController *nav = ((UITabBarController *)tabBarController).selectedViewController;
        topViewController = nav.viewControllers.lastObject;
    }
    if (topViewController) {
        [topViewController.navigationController popToRootViewControllerAnimated:YES];
        tabBarController.selectedIndex = 0;
    }
}

+ (void)routeLoginController:(void(^)(BOOL success))completion {
    UIViewController *login = [NSClassFromString(@"SLLoginViewController") new];
    //login.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [login setValue:completion forKey:@"loginCallback"];
    BasicNavigationController *nav = [[BasicNavigationController alloc] initWithRootViewController:login];
    nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
    UIViewController *root = UIApplication.sharedApplication.keyWindow.rootViewController;
    [root presentViewController:nav animated:YES completion:nil];
}

+ (void)popToRootController {
    UIViewController *ctrl = UIApplication.sharedApplication.keyWindow.rootViewController;
    UIViewController *topViewController = ctrl;
    if ([ctrl isKindOfClass:UINavigationController.class]) {
        topViewController = ((UINavigationController *)ctrl).viewControllers.lastObject;
    } else if ([ctrl isKindOfClass:UITabBarController.class]) {
        //((UITabBarController *)ctrl).tabBar.hidden
        UINavigationController *nav = ((UITabBarController *)ctrl).selectedViewController;
        topViewController = nav.viewControllers.lastObject;
    }
    [topViewController.navigationController popToRootViewControllerAnimated:YES];
}

@end
